<template>
  <div class="login-container">
     <div class="login-logo">
      <div>
        <img class="logo" src="../../../static/logo/headerLogo.png" alt="">
      </div>
      <div style="margin-top:7px">
        <span class="title">排班管理系统</span>
      </div>
    </div>
    <el-form :model="loginForm" :rules="loginRules" ref="loginForm" label-position="left" class="login-form">
      <h3 class="title">
        <!-- <img :src="logo" alt="" > -->
        用户登录
      </h3>
      <el-form-item prop="username">
        <span class="svg-container svg-container_login">
          <svg-icon icon-class="user" />
        </span>
        <el-input name="username" type="text" @change="checkUserName" v-model="loginForm.username" autofocus placeholder="用户/username" />
      </el-form-item>
      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password"></svg-icon>
        </span>
        <el-input :type="pwdType" @keyup.enter.native="handleLogin" v-model="loginForm.password" autoComplete="new-password" placeholder="密码/password"></el-input>
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="pwdType=='password'?'eye-close':'eye'" />
        </span>
      </el-form-item>
      <el-row>
        <el-col :span="17">
          <el-form-item prop="verificationCode">
            <span class="svg-container">
              <svg-icon icon-class="verificationcode"></svg-icon>
            </span>
            <el-input name="verification-code" type="text" @keyup.enter.native="handleLogin" v-model="loginForm.verificationCode"
              placeholder="验证码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5" :offset="1">
          <verification-code @rendom="value=>rendomStr = value"></verification-code>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button type="primary" style="width:100%;" :loading="loading" @click.native.prevent="handleLogin">
          登录
        </el-button>
      </el-form-item>
    </el-form>
    <div class="login-foot">
      <!-- <p>友情链接：
        <a href="http://oa.agree.com.cn:6988/oa/">OA办公管理系统</a>
        <a href="http://mail.agree.com.cn/">263云通讯</a>
      </p> -->
      <p style="font-size: 14px;">Copyright©1993-2018
        <a href="http://www.agree.com.cn">AGREE</a> ALL Right Reserved 版权所有 京ICP备 20000001号</p>
    </div>

    <el-dialog title="选择业务机构列表" :modal="false" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false"
      :visible.sync="dialogTableVisible">
      <el-card>
        <el-table highlight-current-row @current-change="handleCurrentChange" :data="branchTable">
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column property="BranchNum" label="机构号" width="150"></el-table-column>
          <el-table-column property="BranchName" label="姓名"></el-table-column>
        </el-table>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="selectBranch">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改密码" :modal="false" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false"
      :visible.sync="dialogChangePwd">
      <el-card>
        <el-form :model="ruleForm" status-icon :rules="rules2" ref="ruleForm" label-width="120px" class="demo-ruleForm"
          width="40px">
          <el-form-item label="原密码" prop="oldpass">
            <el-input :type="'password'" v-model.number="loginForm.password" :disabled="true" placeholder="请输入原密码"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="pass">
            <el-input :type="'password'" v-model="ruleForm.pass" placeholder="请输入新密码"></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="checkPass">
            <el-input :type="'password'" v-model="ruleForm.checkPass" placeholder="请再次输入新密码"></el-input>
          </el-form-item>
        </el-form>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="clostPw('ruleForm')">取 消</el-button>
        <el-button size="mini" type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import request from "@/common/utils/request";
  import des from "@/common/utils/des";
  import changepd from "@/message/shared/changepd";
  import {
    checkUserName,
    GetKey
  } from "@/message/login/login";
import {
  getUserNum,
  setUserNum,
  getBranchNum,
  setBranchNum,
} from '@/common/utils/auth'
  import {
    isvalidUsername
  } from "@/common/utils/validate";
  import VerificationCode from "@/components/VerificationCode";
  // import logo from "../../../static/images/image/ztlogo.png";
  // import agree from "../../../static/images/image/agree.png";

  export default {
    name: "login",
    data() {
      const validateUsername = (rule, value, callback) => {
        if (value.length > 20) {
          callback(new Error("请输入正确的用户名"));
        } else {
          callback();
        }
      };
      const validatePass = (rule, value, callback) => {
        if (value.length < 5) {
          callback(new Error("密码不能小于5位"));
        } else {
          callback();
        }
      };
      const validateCode = (rule, value, callback) => {
        if (value.toUpperCase() != this.rendomStr.toUpperCase()) {
          callback(new Error("验证码有误！"));
        } else {
          callback();
        }
      };
      var validatePass3 = (rule, value, callback) => {
        if (value.length < 5) {
          callback(new Error("密码不能小于5位"));
        } else if (value === this.loginForm.password) {
          callback(new Error("新密码不能和旧密码相同"));
        } else {
          if (this.ruleForm.checkPass !== "") {
            this.$refs.ruleForm.validateField("checkPass");
          }
          callback();
        }
      };
      var validatePass4 = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请再次输入密码"));
        } else if (value !== this.ruleForm.pass) {
          callback(new Error("两次输入密码不一致!"));
        } else {
          callback();
        }
      };
      return {
        // agree,
        // logo,
        rendomStr: "",
        branchTable: [], // 机构表格
        dialogTableVisible: false,
        dialogChangePwd: false,
        loginForm: {
          username: "",
          password: "",
          password1: "",
          verificationCode: "",
          BranchNum: null // 机构编号
        },
        ruleForm: {
          pass: "",
          checkPass: ""
        },
        loginRules: {
          username: [{
            required: true,
            trigger: "blur",
            validator: validateUsername
          }],
          password: [{
            required: true,
            trigger: "blur",
            validator: validatePass
          }],
          verificationCode: [{
            required: true,
            trigger: "blur",
            validator: validateCode
          }]
        },
        rules2: {
          pass: [{
            validator: validatePass3,
            trigger: "blur"
          }],
          checkPass: [{
            validator: validatePass4,
            trigger: "blur"
          }]
        },
        loading: false,
        pwdType: "password"
      };
    },
    components: {
      VerificationCode
    },
    mounted() {
      // 方便开发 二维码自动填写
      this.loginForm.verificationCode = this.rendomStr;
    },
    computed: {
      
    },
       state: {
    UserNum: getUserNum(),
    BranchNum: getBranchNum(),
  },

  mutations: {
    SET_USERNUM: (state, UserNum) => {
      state.UserNum = UserNum
    },
    SET_BRANCHNUM: (state, BranchNum) => {
      state.BranchNum = BranchNum
    },
  },
    methods: {
      // 选中业务机构
      handleCurrentChange(val) {
        this.currentRow = val;
        this.loginForm.BranchNum = this.currentRow.BranchNum;
      },
      selectBranch() {
        if (this.currentRow != undefined) {
          this.dialogTableVisible = false;
        } else {
          this.$message({
            type: "warning",
            message: "请选择机构"
          });
        }
      },
      /**
       * @desc 校验用户
       */
      checkUserName({
      commit,
      state
    }) {
        let resBody = new checkUserName();
        resBody.data.UserNum = this.loginForm.username;
        request(resBody)
          .then(response => {
            if (response.SYS_HEAD.ReturnCode === "000000") {
                let branchArr = response.RspInfo.BranchList;
                this.loginForm.BranchNum = branchArr[0].BranchNum;
              setUserNum(this.loginForm.username)
              setBranchNum(branchArr[0].BranchNum)
              commit('SET_USERNUM', this.loginForm.username)
              commit('SET_BRANCHNUM', branchArr[0].BranchNum)
              // let branchArr = response.RspInfo.BranchList;
              if (branchArr.length > 1) {
                this.branchTable = branchArr;
                this.dialogTableVisible = true;
              } else {
                this.loginForm.BranchNum = branchArr[0].BranchNum;
              }
            } else {
              this.loginForm.username = ""
              this.loginForm.BranchNum = ""
              this.loginForm.password = ""
              this.$message({
                type: "warning",
                message: response.SYS_HEAD.ReturnMessage
              });
            }
          })
          .catch(error => {
            this.loading = false;
            console.log(error);
          });
      },

      showPwd() {
        this.pwdType = this.pwdType == "password" ? "" : "password";
      },
      clostPw(formName) {
        this.$refs[formName].resetFields();
        this.dialogChangePwd = false;
        this.loading = false;
      },
      submitForm(formName) {
        this.loading = false;
        this.$refs[formName].validate(valid => {
          if (valid) {
            let resBody = new GetKey();
            let key = "";
            request(resBody).then(response => {
              if (response.APP_HEAD.ReturnCode === "000000") {
                const keyList = response.RspInfo.Result || [];
                keyList.forEach(item => {
                  if (item.PARAKEY === "EncnPswd") {
                    key = item.PARAVALUE;
                  }
                });
                let resBody1 = new changepd();
                resBody1.data.UserNum = this.loginForm.username;
                resBody1.data.OldUserPwd = des.encryptByDES(
                  this.loginForm.password + "",
                  key
                );
                resBody1.data.UserPwd = des.encryptByDES(
                  this.ruleForm.pass + "",
                  key
                );
                request(resBody1)
                  .then(response => {
                    if (response.SYS_HEAD.ReturnCode === "000000") {
                      this.isShow = false;
                      this.$message({
                        message: "密码更改成功",
                        type: "success"
                      });
                      this.loginForm.password = '';
                      this.dialogChangePwd = false;
                    } else {
                      this.$message.error({
                        message: response.SYS_HEAD.ReturnMessage,
                        // type: "error"
                      });
                    }
                  })
                  .catch(error => {
                    console.log("error", error);
                  });
              } else {
                this.$message({
                  message: "修改密码失败!",
                  type: "error"
                });
                return;
              }
            });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },

      handleLogin() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true;
            const resBody = new GetKey();
            let key = "";
            request(resBody)
              .then(response => {
                if (response.APP_HEAD.ReturnCode === "000000") {
                  const keyList = response.RspInfo.Result || [];
                  keyList.forEach(item => {
                    if (item.PARAKEY === "EncnPswd") {
                      key = item.PARAVALUE;
                    }
                  });
                  this.loginForm.password1 = des.encryptByDES(
                    this.loginForm.password,
                    key
                  );
                }
              })
              .then(() => {
                this.$store
                  .dispatch("Login", this.loginForm)
                  .then(data => {
                    if (
                      data.SYS_HEAD.ReturnCode === "000000" && data.RspInfo.PwdStatus !== "1" ) {
                      this.loading = false;
                      if (data.RspInfo.PwdStatus === "2") {
                        this.$message({
                          type: "warning",
                          message: "密码即将过期,请及时更换密码"
                        });
                      } else {
                        this.$message({
                          type: "success",
                          message: "登录成功"
                        });
                      }
                      this.$router.push({
                        path: "/home/index",
                        name: "homeIndex",
                        params: {
                          firstLog: this.$store.getters.isFirstLoginFLag,
                          firstLogMessage: data.SYS_HEAD.ReturnMessage
                        }
                      });
                    } else if ( data.SYS_HEAD.ReturnCode === "000000" && data.RspInfo.PwdStatus === "1") {
                      this.$message.error({
                        // type: "error",
                        message: "密码为初始密码,请修改!"
                      });
                      this.dialogChangePwd = true;
                    } else if(data.SYS_HEAD.ReturnCode === "IBSYSC017"){
                      this.$message.error({
                        // type: "error",
                        message: "密码已过期,请修改!"
                      });
                      this.dialogChangePwd = true;
                    } else {
                      this.loading = false;
                      this.$message({
                        type: "error",
                        // message: "返回异常"
                        message: data.SYS_HEAD.ReturnMessage
                      });
                    }
                  })
                  .catch(error => {
                    
                    this.loading = false;
                    this.$message({
                      type: "info",
                      // message: "代码异常"
                      message: data.ReturnMessage
                    });
                  });
              });
          } else {
            // console.log("error submit!!");
            return false;
          }
        });
      }
    }
  };

</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  $bg: #2d3a4b; //#474d63 2d3a4b
  $dark_gray: #889aa4;
  // $light_gray: #eee;
  $light_gray: #333;

  .login-container /deep/ {
    position: fixed;
    height: 100%;
    width: 100%;
    background-color: $bg;

    // background: url("../../assets/image/back.png");
    input:-webkit-autofill {
      // box-shadow: 0 0 0px 1000px #293444 inset !important;
      box-shadow: 0 0 0px 1000px #ecf5fa inset !important;
      // -webkit-text-fill-color: #fff !important;
    }

    .el-form {
      // background: $bg;
      background: #ffffff;
      opacity: 0.9;
      border-radius: 3px;
    }

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
    }

    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;
    }

    .tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;

      &_login {
        font-size: 20px;
      }
    }

    .title {
      font-size: 20px;
      font-weight: 400;
      color: $light_gray;
      margin: 0px auto 20px auto;
      text-align: center;
      font-weight: bold;
      position: relative;

      img {
        position: absolute;
        width: 100px;
        height: 100px;
        top: -100px;
        left: 110px;
      }
    }

    .login-form {
      position: absolute;
      // left: 0;
      // right: 0;
      width: 400px;
      padding: 35px 35px 25px 35px;
        // margin: 120px auto;
      top: 50%;
      left: 50%;
      //兼容IE9
      overflow:auto;
      margin-left:-200px;
      margin-top:-200px;
      //兼容IE9
      // transform: translate(-50%, -50%);
      // -webkit-transform: translate(-50%, -50%);
      // -moz-transform: translate(-50%, -50%);
      // -ms-transform: translate(-50%, -50%);
      // -o-transform: translate(-50%, -50%);
      z-index: 500;
    }

    .el-form-item {
      // border: 1px solid rgba(255, 255, 255, 0.1);
      border: 1px solid #d8d8d8;
      // background: rgba(0, 0, 0, 0.1);
      background: #ecf5fa;
      border-radius: 5px;
      color: #454545;
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }

    .thirdparty-button {
      position: absolute;
      right: 35px;
      bottom: 28px;
    }

    /* 登陆页logo */
    .login-logo {
      position: absolute;
      top: 20px;
      left: 20px;

      .logo {
        height: 34px;
        // width: 140px;
        // margin: 14px 17px;
        
      }

      .title {
        font-size: 20px;
        color: #eeeeee;
      }

      div {
        float: left;
        margin-right: 20px;
      }
    }

    .login-foot {
      color: #999999;
      position: absolute;
      bottom: 20px;
      left: 0;
      text-align: center;
      width: 100%;
    }
  }

  // .verification-code {
  //   margin-top: 1px;
  // }

</style>
